import axios, {AxiosInstance, AxiosResponse} from "axios"
import {ElMessage} from 'element-plus'

const handleCode = async (code: number, msg: string) => {
    switch (code) {
        case 401:
            ElMessage.error(msg || '登录失效')
            setTimeout(() => {
                console.log('登录失效')
            }, 1500)
            // 跳转登录
            break
        default:
            ElMessage.error(msg || `后端接口${code}异常`)
            break
    }
}

//创建axsio 赋给常量service
const request: AxiosInstance = axios.create({
    baseURL: import.meta.env.VITE_APP_BASE_URL,
    timeout: 30000,
    headers: {
        'Content-Type': 'application/json;charset=UTF-8',
        'Access-Control-Allow-Origin': "*"
    }
});
// 添加请求拦截器
request.interceptors.request.use(
    (config: any) => {
        console.log(config, 'config')
        return config;
    },
    (error: any) => {
        // 对请求错误做些什么
        console.log(error, 'error')
        return Promise.reject(error);
    }
);
// 添加响应拦截器
request.interceptors.response.use(
    (response: AxiosResponse) => {
        //response参数是响应对象
        // 对响应数据做点什么
        const {data, config} = response
        return data;
    },
    (error: any) => {
        const {response} = error

        if (error.response && error.response.data) {
            const {status, data} = response
            handleCode(status, data.msg)

            // 对响应错误做点什么
            return Promise.reject(error);
        } else {
            let {message} = error
            if (message === 'Network Error') {
                message = '后端接口连接异常'
            }
            if (message.includes('timeout')) {
                message = '后端接口请求超时'
            }
            if (message.includes('Request failed with status code')) {
                const code = message.substr(message.length - 3)
                message = '后端接口' + code + '异常'
            }
            message.error(message || `后端接口未知异常`)
            return Promise.reject(error);
        }
    }
);

export default request;